package controllers

import (
	"Doge/common/random"
	"Doge/common/requests"
	"Doge/common/responses"
	"Doge/enum/code"
	"Doge/enum/fileds"
	"Doge/models"
	"Doge/repositories"
	"github.com/labstack/echo/v4"
	"net/http"
	"time"
)

type DelayedController struct {
	repository *repositories.DelayedManager
}

func NewDelayedController() (delayedController *DelayedController, err error) {
	var (
		delayedManager *repositories.DelayedManager
	)

	if delayedManager, err = repositories.NewDelayedManager(); err != nil {
		return &DelayedController{}, err
	}
	return &DelayedController{
		repository: delayedManager,
	}, err
}

func (controller *DelayedController) GetDelayed(c echo.Context) error {
	return c.JSON(http.StatusOK, responses.Response(200, "成功", ""))
}

func (controller *DelayedController) SaveDelayed(c echo.Context) error {
	var (
		v      *requests.DelayedRequest
		id     string
		s      *models.Delayed
		second int
		err    error
	)

	v = new(requests.DelayedRequest)
	if err = c.Bind(v); err != nil {
		return c.JSON(http.StatusOK, responses.Response(code.ParameterError, "绑定参数失败", err))
	}
	if v.Second < -1 {
		return c.JSON(http.StatusOK, responses.Response(code.ParameterError, "延迟时间不能为空", ""))
	}
	if v.Command == "" {
		return c.JSON(http.StatusOK, responses.Response(code.ParameterError, "command不能为空", ""))
	}
	s = new(models.Delayed)
	s.ID = random.RandDateAndString(17)
	s.Name = v.Name
	s.Command = v.Command
	if v.Second == -1 || v.Second == 0 {
		second = 1
	} else {
		second = v.Second
	}

	s.RunAt = time.Now().Add(time.Second * time.Duration(second)).Format("2006-01-02 15:04:05") //TODO 计算出来的时间
	s.CreateAt = time.Now().Format("2006-01-02 15:04:05")
	s.Status = fileds.Unexecuted

	if id, err = controller.repository.InsertDelayed(s); err != nil {
		return c.JSON(http.StatusOK, responses.Response(code.QueryError, "报错错误", err))
	}

	return c.JSON(http.StatusOK, responses.Response(200, "成功", id))

	return c.JSON(http.StatusOK, responses.Response(200, "成功", ""))
}
